package memory.InitializeAndFree;

/**
 * @Author wsyjiamian@163.com
 * @Description 内存释放
 * @Date 2020/8/17 14:57
 */

public class Free {
    public static void main(String[] args) {
        int i=0;

        /**
         执行下面的代码，你可能会出现finalize方法根本没有被调用。
         **/
        /*User u = new User("zs" , i);
        System.gc();
        System.out.println(u.age);
        */
        while(true){
            User u = new User("zs" , i);
            System.out.println(u.age);
            try {
                i ++;
                u = null;
                //if(i % 100 == 0)
                    System.gc();
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class User{
        String name;
        int age;
        public User(String name , int age){
            this.name = name;
            this.age = age;
        }
        @Override
        protected void finalize() throws Throwable {
            System.out.println("当前age=" + this.age+" 被回收");
        }
    }
}
